import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/config/theme.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../../config/const.dart';

///
///
/// Dialog内容基类
/// 添加标题、内容、按钮
///
/// 当child含有TextFiled时，响应焦点后内容会跟随键盘弹起
/// 关键代码：
/// AnimatedPadding
///   - padding: MediaQuery.of(context).viewInsets,
///
///
/// Flutter bottomSheet 实现跟随键盘弹起方式
/// showModalBottomSheet(
///       context: Get.context!,
///       isScrollControlled: true,
///       builder: (BuildContext context) {
///         return AnimatedPadding(
///           padding: MediaQuery.of(context).viewInsets,
///           duration: const Duration(milliseconds: 100),
///           child: content,
///         );
///       },
///     )
///
///
///
class DialogContentView extends StatelessWidget {
  const DialogContentView({
    Key? key,
    this.child,
    this.title,
    this.titleTextStyle,
    this.titleWidget,
    this.titlePadding,
    this.content,
    this.contentTextStyle,
    this.contentWidget,
    this.contentPadding,
    this.cancel,
    this.confirm,
    this.onCancel,
    this.onConfirm,
    this.onTapEvent,
    this.bottomWidget,
    this.bottomPadding,
    this.titleMaxHeight,
    this.contentMinHeight,
    this.contentMaxHeight,
    this.backgroundColor,
    this.borderRadius,
    this.insetPadding,
  }) : //assert(titlePadding != null),
        super(key: key);

  /// child 一般不传，会覆盖标题、内容、按钮等所有内容
  final Widget? child;

  /// 重置密码
  final String? title;
  final TextStyle? titleTextStyle;
  final Widget? titleWidget;
  final EdgeInsetsGeometry? titlePadding;
  final String? content;
  final TextStyle? contentTextStyle;
  final Widget? contentWidget;
  final EdgeInsetsGeometry? contentPadding;
  final String? cancel;
  final String? confirm;
  final VoidCallback? onCancel;
  final VoidCallback? onConfirm;
  final VoidCallback? onTapEvent;
  final Widget? bottomWidget;
  final EdgeInsetsGeometry? bottomPadding;
  final double? titleMaxHeight;
  final double? contentMaxHeight;
  final double? contentMinHeight;
  final Color? backgroundColor;
  final BorderRadiusGeometry? borderRadius;
  final EdgeInsets? insetPadding;

  @override
  Widget build(BuildContext context) {
    // 计算Dialog宽度
    double alertWidth = Get.width;
    if (insetPadding != null) {
      alertWidth -= ((insetPadding?.left ?? 0) + (insetPadding?.right ?? 0));
    }

    // 计算按钮宽度
    double buttonWidth = (cancel != null && confirm != null)
        ? (alertWidth - CONTENT_MARGIN * 4) / 2
        : (alertWidth - CONTENT_MARGIN * 2);

    // 底部按钮
    List<Widget> actions = [];
    if (cancel != null) {
      Widget cancelWidget = _buildButton(cancel, false, buttonWidth, () {
        if (onTapEvent != null) onTapEvent!();
        if (onCancel != null) onCancel!();
      });
      actions.add(cancelWidget);
    }
    if (confirm != null) {
      Widget confirmWidget = _buildButton(confirm, true, buttonWidth, () {
        if (onTapEvent != null) onTapEvent!();
        if (onConfirm != null) onConfirm!();
      });
      actions.add(confirmWidget);
    }

    Widget dialogChild = Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Visibility(
          visible: titleWidget != null || title != null,
          child: Container(
            padding: titlePadding ??
                const EdgeInsets.only(top: 15, bottom: 15, left: 20, right: 20),
            constraints: BoxConstraints(maxHeight: titleMaxHeight ?? 200.h),
            child: Visibility(
              visible: titleWidget != null,
              replacement: AutoSizeText(
                title ?? '',
                style: lxTheme.appbarTitleStyle,
                textAlign: TextAlign.center,
                maxLines: 5,
                minFontSize: 13,
                overflow: TextOverflow.ellipsis,
              ),
              child: titleWidget ?? const SizedBox.shrink(),
            ),
          ),
        ),
        Container(
          constraints: BoxConstraints(
              maxHeight: contentMaxHeight ??
                  Get.height * 0.55 +
                      (actions.isNotEmpty ? 0 : bottomButtonHeight),
              minHeight: contentMinHeight ?? 100.h),
          padding: contentPadding ?? const EdgeInsets.only(left: 20, right: 20),
          child: SingleChildScrollView(
            padding: EdgeInsets.zero,
            child: Visibility(
                visible: contentWidget != null,
                child: contentWidget ?? const SizedBox.shrink(),
                replacement: Container(
                    constraints: BoxConstraints(
                      maxHeight: Get.height * 0.55 +
                          (actions.isNotEmpty ? 0 : bottomButtonHeight),
                    ),
                    child: SingleChildScrollView(
                      child: Container(
                        padding: const EdgeInsets.only(top: 20, bottom: 20),
                        alignment: Alignment.topLeft,
                        child: Text(
                          content ?? '',
                          style: contentTextStyle ??
                              TextStyle(
                                  fontSize: 16.0,
                                  color: Theme.of(Get.context!)
                                      .colorScheme
                                      .subtitleColor,
                                  fontWeight: FontWeight.w400),
                        ),
                      ),
                    ))),
          ),
        ),
        Visibility(
            visible: bottomWidget != null,
            child: Container(
              padding:
                  bottomPadding ?? const EdgeInsets.only(left: 20, right: 20),
              child: bottomWidget ?? const SizedBox.shrink(),
            )),

        // 底部按钮
        Visibility(
          visible: actions.isNotEmpty,
          child: Container(
            margin: EdgeInsets.only(top: 15, bottom: 20 + screenBottom * 0.3),
            height: bottomButtonHeight,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: actions,
            ),
          ),
          // 没有按钮时，底部添加间隔
          replacement: Visibility(
            visible: content != null,
            // 纯文本间隔
            child: SizedBox(height: 50.h),
            // 自定义content内容间隔
            replacement: SizedBox(height: 20.h),
          ),
        ),
        // 全面屏间隔
        SizedBox(height: screenBottom * 0.5)
      ],
    );
    return _animatedWidget(context, child ?? dialogChild);
  }

  ///
  /// Dialog内容基类
  /// 当child含有TextFiled时，响应焦点后内容会跟随键盘弹起
  ///
  /// 关键代码：
  /// AnimatedPadding
  ///   - padding: MediaQuery.of(context).viewInsets,
  ///
  Widget _animatedWidget(BuildContext context, Widget child) {
    final EdgeInsets effectivePadding =
        MediaQuery.of(context).viewInsets + (insetPadding ?? EdgeInsets.zero);

    return AnimatedPadding(
      padding: effectivePadding,
      duration: const Duration(),
      // curve: Curves.decelerate,
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: ConstrainedBox(
          constraints:
              BoxConstraints(minWidth: MediaQuery.of(context).size.width),
          child: Material(
            color: backgroundColor ?? Theme.of(context).dialogBackgroundColor,
            elevation: 24,
            shape: RoundedRectangleBorder(
                borderRadius: borderRadius ??
                    const BorderRadius.only(
                        topLeft: Radius.circular(16),
                        topRight: Radius.circular(16))),
            type: MaterialType.card,
            clipBehavior: Clip.none,
            child: child,
          ),
        ),
      ),
    );
  }

  ///
  /// 底部按钮
  /// title: 按钮标题
  /// highlight: 是否是高亮按钮（橙色）
  /// style: 按钮风格
  static Widget _buildButton(
      String? title, bool highlight, double? width, void Function() onPressed) {
    return LxButton(
      borderRadius: BorderRadius.circular(200 / 2),
      title: title,
      buttonAlignmentEnum: ButtonAlignmentEnum.block,
      fontWeightEnum: LxFontWeightEnum.bodyLarge,
      onTap: onPressed,
    );
  }
}
